import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';

import { Sequelize } from 'sequelize-typescript';

import { User } from './users.model';

@Injectable()
export class UsersService {
  constructor(
    @InjectModel(User) private userModel: typeof User,
    private sequelize: Sequelize
  ) {}

  async findAll(): Promise<User[]> {
    return this.userModel.findAll();
  }

  // sql 查询 ： https://www.bookstack.cn/read/tuture-Nest-js/bbfde134214ecbe1.md
  findOne(id: number): Promise<User | undefined> {
    //return this.userModel.findByPk(id, { rejectOnEmpty: true})
    //return this.userModel.findOne({where: { id: {[Op.gt]: id} } });
    // 参考 https://www.sequelize.cn/other-topics/typescript
    return this.userModel.findOne<User>({ rejectOnEmpty: undefined, where: { id: id }, attributes: ['id', 'name'] })
      .then(function(result) {
        return result;
      }).catch(function(error) {
        return null;
      });
  }

  async remove(id: number): Promise<void> {
    const user = await this.findOne(id);
    await user.destroy();
  }
}